package cn.edu.hncj.aspect;

import cn.edu.hncj.annotation.MyPermission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.ma
 * @since 2022/11/13 22:17
 **/
@Component
@Aspect
public class PermissionAdvice {
    private List<String> permissions=new ArrayList<String>();

    public PermissionAdvice(){
        permissions.add("list");
        permissions.add("delete");
        permissions.add("update");
    }
    @Pointcut("@annotation(cn.edu.hncj.annotation.MyPermission)")
    public void permissionPointcut(){}

    @Around("permissionPointcut()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        MyPermission annotation = method.getAnnotation(MyPermission.class);
        if(annotation!=null){
            String value = annotation.value();
            if(!permissions.contains(value)){
                return  "没有权限";
            }
        }

        return joinPoint.proceed();
    }
}
